import {
  // BadRequestException,
  ConflictException,
  Injectable,
  UsePipes,
  ValidationPipe,
} from '@nestjs/common';
import { CreateTest2Dto } from './dto/create-test2.dto';
import { UpdateTest2Dto } from './dto/update-test2.dto';
import { Test2 } from './entities/test2.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
// import { validateOrReject } from 'class-validator';

@Injectable()
export class Test2Service {
  constructor(
    @InjectRepository(Test2)
    private readonly test2Repository: Repository<Test2>,
  ) {}

  @UsePipes(new ValidationPipe())
  async create(createTest2Dto: CreateTest2Dto) {
    // 手动验证 DTO
    // try {
    //   await validateOrReject(createTest2Dto);
    // } catch (errors) {
    //   throw new BadRequestException(errors);
    // }
    // 这里是插入数据逻辑，如果id重复则会抛出异常
    try {
      /**
       * insert 直接插入数据，如果id重复则会抛出异常，此处捕获异常并抛出冲突异常
       * create和save，create先创建实例，可以做校验，然后再save到数据库
       */
      const result = await this.test2Repository.create(createTest2Dto);
      return this.test2Repository.save(result);
    } catch (error) {
      if (error.code === 'ERR_DUP_ENTRY') {
        throw new ConflictException('id already exist');
      }
      throw error;
    }
  }

  async findAll(): Promise<Test2[]> {
    return this.test2Repository.find();
  }
  clear() {
    return this.test2Repository.clear();
  }

  findOne(id: number) {
    return this.test2Repository.findOneBy({ id });
  }

  update(id: number, updateTest2Dto: UpdateTest2Dto) {
    return this.test2Repository.update(id, updateTest2Dto);
  }

  remove(id: number) {
    return this.test2Repository.delete(id);
  }

  async removeList(ids: number[]) {
    return await this.test2Repository
      .createQueryBuilder()
      .delete()
      .from(Test2)
      .whereInIds(ids)
      .execute();
  }
}
